<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home'}">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addRoleDialog">添加角色</el-button>
                </el-col>
            </el-row>
            <el-table :data="rolesList">
                <el-table-column  type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom',i1===0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                            <!-- 一级权限 -->
                            <el-col :span="5">
                                <el-tag closable  @close="removeRoleByID(scope.row,item1.id)">
                                    {{item1.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级权限 -->
                            <el-col :span="19">
                                <!-- 通过for循环嵌套渲染二级权限 -->
                                <el-row :class="[i2===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRoleByID(scope.row,item2.id)">
                                            {{item2.authName}}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" :span="18" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRoleByID(scope.row,item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                        <!-- <pre>
                            {{scope.row}} 
                        </pre> -->
                    </template>
                </el-table-column>
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" prop="id">
                    <template slot-scope="scope">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRoleDialog(scope.row.id)">编辑</el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoleDialog(scope.row.id)">删除</el-button>
                            <el-tooltip class="item" effect="dark" content="分配权限" placement="top" :enterable="false">
                                 <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRolesDialog(scope.row)">分配权限</el-button>
                            </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加用户角色对话框 -->
        <el-dialog
        title="提示"
        :visible.sync="addRoleVisible"
        width="50%"
        @close='addRoleClosed'
        >
            <el-form :model="addRoleForm" :rules="addRoleRules" ref="addRoleRef" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRoleHandle">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑用户角色对话框 -->
        <el-dialog
        title="提示"
        :visible.sync="editRoleVisible"
        width="50%"
        @close="editRoleClosed"
        >
            <el-form :model="editRoleForm" :rules="addRoleRules" ref="editRoleRef" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRoleConfirm">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配用户权限对话框 -->
        <el-dialog
        title="提示"
        :visible.sync="setRoleVisible"
        width="50%"
        @close="setRoleClosed"
        >
        <!-- 设置用户数据源树形结构展示 -->
            <el-tree ref="treeRef" :data="setRoleList" :props="treeProps"  show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleVisible = false">取 消</el-button>
                <el-button type="primary" @click="allowRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    created(){
        this.getRolesList()
    },
    data(){
        return {
            //所有角色列表数据
            rolesList:[],
            //添加角色对话框的数据对象
            addRoleForm:{
                roleName:'',
                roleDesc:''
            },
            //添加对话框的校验规则对象
            addRoleRules:{
                roleName:[
                    {required:true,message:'角色名称不能为空',tigger:'blur'}
                ],
                roleDesc:[
                    {required:true,message:'角色描述不能为空',tigger:'blur'}
                ]
            },
            //添加对话框的显示与隐藏
            addRoleVisible:false,
            //修改用户对话框的显示与隐藏
            editRoleVisible:false,
            //分配用户权限对话框的显示与隐藏
            setRoleVisible:false,
            //修改用户对话框的数据对象
            editRoleForm:{},
            //获取用户角色分配权限
            setRoleList:[],
            //树形结构与数据源的匹配
            treeProps:{
                label:'authName',
                children:'children'
            },
            //树形结构默认选中匹配的数据
            //默认选中节点id值的数组
            defKeys:[],
            //分配权限时用到的Id
            roleId:''
        }
    },
    methods:{
        //获取所有角色列表
        async getRolesList(){
            const {data:res}=await this.$http.get('roles')
            if(res.meta.status!==200){return this.$message.error("获取角色列表失败")}
            this.rolesList=res.data
        },
        //删除权限
       async removeRoleByID(role,rightId){
            const confirmReslut=await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err)
            if(confirmReslut!=='confirm'){
                return this.$message.info("已取消删除操作")
            }
            const {data:res}=await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
            if(res.meta.status!==200){return this.$message.error('删除权限失败')}
            this.$message.success('删除权限成功')
            //整个列表会刷新
            // this.getRolesList()
            //我们只需要局部数据的变化
            //把服务器返回的最新权限直接赋值给children属性
            role.children=res.data
        },
        //显示添加对话框
        addRoleDialog(){
            this.addRoleVisible=true
        },
        //重置添加表单及其校验规则
        addRoleClosed(){
            this.$refs.addRoleRef.resetFields()
        },
        //确定校验及请求数据
        addRoleHandle(){
            this.$refs.addRoleRef.validate(async valid=>{
                if(!valid) return
                const {data:res}=await this.$http.post('roles',this.addRoleForm)
                if(res.meta.status!==201){return this.$message.error('添加用户失败')}
                this.getRolesList()
                this.$message.success('添加用户成功')
                this.addRoleVisible=false
            })
        },
        //通过id查询出用户数据再去dialog对话渲染
        async editRoleDialog(id){
            this.editRoleVisible=true
            const {data:res}=await this.$http.get('roles/'+id)
            if(res.meta.status!==200){return this.$message.error('查询用户信息失败')}
            this.editRoleForm=res.data
        },
        //重置修改表单数据
        editRoleClosed(){
            this.$refs.editRoleRef.resetFields()
        },
        //修改角色名称
        editRoleConfirm(){
            this.$refs.editRoleRef.validate(async valid=>{
                if(!valid) return
                const {data:res}=await this.$http.put('roles/'+this.editRoleForm.roleId,{roleName:this.editRoleForm.roleName,roleDesc:this.editRoleForm.roleDesc})
                if(res.meta.status!==200){return this.$message.error('修改用户信息失败')}
                this.getRolesList()
                this.$message.success('修改用户信息成功')
                this.editRoleVisible=false
            })
        },
        //删除角色
        async deleteRoleDialog(id){
            const {data:res}=await this.$http.delete('roles/'+id)
            if(res.meta.status!==200){return this.$message.error('删除角色失败')}
            this.getRolesList()
            this.$message.success('删除角色成功')
        },
        //分配权限对话框的显示与隐藏
        async showSetRolesDialog(role){
            this.roleId=role.id
            const {data:res}=await this.$http.get('rights/tree')
            if(res.meta.status!==200){return this.$message.error("获取用户列表失败")}
            this.setRoleList=res.data
            this.$message.success("获取用户列表成功")
            //递归获取三级节点的id
            this.getLeafKeys(role,this.defKeys)
            this.setRoleVisible=true
        },
        //通过递归的形式,获取角色下所有三级权限的id并保存到defKeys数组中
        getLeafKeys(node,arr){
            if(!node.children){
                return arr.push(node.id)
            }
            
            node.children.forEach(item=>this.getLeafKeys(item,arr))
        },
        //关闭分配权限对话框后清空defKeys数组防止前后权限叠加
        setRoleClosed(){
            this.defKeys=[]
        },
        //点击为角色分配权限
        async allowRights(){
            var keys=[
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            var idStr=keys.join(',')
            const {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
            if(res.meta.status!==200){return this.$message.error('分配角色权限失败')}
            this.getRolesList()
            this.$message.success('分配角色权限成功')
            this.setRoleVisible=false
        }
    }
}
</script>

<style lang="less" scoped>
    .el-tag{
        margin: 7px;
    }
    .bdtop{
        border-top: 1px solid #eee;
    }
    .bdbottom{
        border-bottom: 1px solid #eee;
    }
    .vcenter{
        display: flex;
        align-items: center;
    }
</style>